package com.example.demo.arithmetic.datastructure.tree;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

//class TreeNode {
//    int val;
//    TreeNode left;
//    TreeNode right;
//
//    TreeNode(int x) {
//        val = x;
//    }
//}

public class Leetcode98 {

    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        TreeNode curr = root;

        while (curr != null || !stack.isEmpty()) {
            // 将左子树所有节点压入栈中  
            while (curr != null) {
                stack.push(curr);
                curr = curr.left;
            }

            // 弹出栈顶节点并访问，然后遍历其右子树  
            curr = stack.pop();
            result.add(curr.val);
            curr = curr.right;
        }

        return result;
    }

    public boolean isValidBST(TreeNode root) {
        List<Integer> result = inorderTraversal(root);
        for (int i = 0; i < result.size() - 1; i++) {
            if (result.get(i) >= result.get(i + 1)) {
                return false;
            }
        }
        return true;
    }

    // 示例使用  
    public static void main(String[] args) {
        // 构造一个简单的BST进行测试  
        TreeNode root = new TreeNode(4);
        root.left = new TreeNode(2);
        root.right = new TreeNode(5);
        root.left.left = new TreeNode(1);
        root.left.right = new TreeNode(3);

        Leetcode98 traversal = new Leetcode98();
        List<Integer> result = traversal.inorderTraversal(root);

        // 输出中序遍历结果  
        for (int val : result) {
            System.out.print(val + " ");
        }
    }
}